package vooga.xml;


public class XMLDocument
{
    private java.util.Map<String, XMLHandler> myHandlers;


    public XMLDocument ()
    {
        myHandlers = new java.util.TreeMap<String, XMLHandler>();
    }


    public void registerHandler (String tag, XMLHandler handler)
    {
        myHandlers.put(tag, handler);
        handler.setDocument(this);
    }

    public XMLHandler getHandler (String tag) throws XMLException
    {
        if (myHandlers.containsKey(tag))
        {
            return myHandlers.get(tag);
        }
        // match any tag (probably only useful for debugging)
        else if (myHandlers.containsKey(""))
        {
            return myHandlers.get("");
        }
        else
        {
            throw new XMLException("No handler registered for " + tag);
        }
    }


    public org.w3c.dom.Node loadFromFile (java.io.File file) throws XMLException
    {
        try
        {
            org.w3c.dom.Document d = 
                javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().
                    parse(file);
            return d.getFirstChild();
        }
        catch (Exception e)
        {
            throw new XMLException("Could not load XML file " + file.getName());
        }
    }


    public Object loadFile (java.io.File file, Object context) throws XMLException
    {
        org.w3c.dom.Node root = loadFromFile(file);
        return getHandler(root.getNodeName()).handleNode(root, context);
    }


    public static void main (String[] args) throws XMLException
    {
        String filename = (args.length > 0) ? filename = args[0] : "example.xml";

        XMLDocument doc = new XMLDocument();
        // make a simple handler that handles any tag
        doc.registerHandler("", new vooga.xml.handlers.PrintHandler());

        System.out.println(doc.loadFile(new java.io.File(filename), new vooga.xml.handlers.Counter()));
    }
}
